package com.example.myblog.controller;

import com.example.myblog.domain.User;
import com.example.myblog.service.user.UserServiceImpl;
import com.example.myblog.util.COOKIEUtil;
import com.example.myblog.util.MD5;
import com.example.myblog.util.SendMail;
import com.example.myblog.util.UUIDUtil;
import jdk.nashorn.internal.objects.NativeJSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.naming.spi.DirStateFactory;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.util.*;
import java.util.logging.Logger;

/**
 * @Author: Wu YunXia
 * @Description: 用户
 * @Date: Created in 10:12 2020/11/26
 * @Modefied By: 2021-08-17
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    HttpServletRequest request;
    @Resource
    HttpServletResponse response;


    @Resource
    UserServiceImpl userService;

    @Autowired
    SendMail sendMail;



    Map map = new HashMap();


    /**
     *  cookie状态
     */
    private String getCookie(){
        String i = null;

        Cookie cookie = COOKIEUtil.getCookieByName(request,"ps");
        Cookie limitCookie = COOKIEUtil.getCookieByName(request,"limitName");
//        System.out.println("cookie:"+cookie);
//        System.out.println("limitCookie:"+limitCookie);
        if(cookie!=null){
            String uuid = cookie.getValue();
            String limits = limitCookie.getValue();
            System.out.println("limits:"+limits);
            System.out.println("uuid:"+uuid);

            if(uuid==null || limits==null){
                map.put("code", 13);
                map.put("msg", "请登录");
            }else{
                List<User> list = userService.queryForUuid(uuid);
                System.out.println("list:"+list);

                if(list.size()!=0){
                    int uid = list.get(0).getId();
                    String trueLimits = list.get(0).getLimits();

                    System.out.println("trueLimits:"+trueLimits);
                    if(uid>0) {
                        i = trueLimits;

                    }else{
                        map.put("code", 13);
                        map.put("msg", "用户不存在");
                    }
                }else{
                    map.put("code", 13);
                    map.put("msg", "登录过期");
                }

            }
        }else{
            map.put("code", 13);
            map.put("msg", "请登录");
        }


        return i;
    }





    @RequestMapping("/responseEntity.do")
public ResponseEntity responseEntity(){
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("message", "Hello Wrold");
    return new ResponseEntity(map, HttpStatus.OK);
}




    /**
     * 添加  修改
     * @return
     */
    @RequestMapping(value = "/addOrUpdateUser",method = RequestMethod.POST)
    public Object addUser(@RequestBody User user){
        int id = user.getId();

        String cookieValue = this.getCookie();
        if(cookieValue==null) return map;
        String[] lists = cookieValue.split("-");

        System.out.println("lists:"+cookieValue);
        System.out.println("contains:"+Arrays.asList(lists).contains("0"));
        System.out.println("contains:"+Arrays.asList(lists).contains("2"));
        /**
         * 超 或 改
         */
        if(!Arrays.asList(lists).contains("0") && user.getLimits().indexOf("0")!=-1){ //不是超 添加超的时候
            map.put("code", -1);
            map.put("msg", "没有权限管理超级管理员");
            return map;
        }
        if(Arrays.asList(lists).contains("0") || Arrays.asList(lists).contains("2")){

            String password = user.getPassword();
//            String random = Math.random()*1000;
            String uuid = UUIDUtil.getUUID(12);
            String mdrandom = MD5.stringToMD5(uuid);

            user.setPsUuid(mdrandom);

            int updateOrAdd;
            String msg = "添加";
            if(id>0){
                updateOrAdd = userService.updateUser(user);
                msg = "更新";
            }else{

                updateOrAdd = userService.addUser(user);
            }

            System.out.println("userStatus:"+updateOrAdd);
            if(updateOrAdd>0){
                map.put("code", 200);
                map.put("msg", msg+"成功");
            }else{
                map.put("code", -1);
                map.put("msg", msg+"失败");
            }
        }else{
            map.put("code", -1);
            map.put("msg", "没有权限");
        }



        return map;
    }


    /**
     * 根据uuid查询 id  uid被操作的用户id  uuid 当前登录的用户 uuid
     */
    @RequestMapping("/editSelf")
    public Object queryId(@RequestParam int uid, @RequestParam String uuid){
        String value = this.getCookie();

        if(value==null) return map;

        String[] lists = value.split("-");

        /**
         * 超
         */
        if(Arrays.asList(lists).contains("0")){
            return true;
        }

        User queryId = userService.queryIdByUuid(uuid); //当前登录的用户 信息
//        queryId.getLimits();
        Arrays.asList(queryId.getLimits()).contains("0");

        System.out.println("isSelf:"+queryId);
        if(queryId!=null){
            if(queryId.getId()==uid){
                return true;
            }
        }
        return false;
    }


    /**
     * 获取全部
     */
    @RequestMapping( "/getUserAll")
    public Object getUserAll(){
        String value = this.getCookie();
        System.out.println("value:"+value);

        if(value==null) return map;

        List<User> userList = userService.getUserAll();
        List<User> result = new ArrayList<>();

        for (User user : userList) {
            user.setPassword("");
            user.setPsUuid("");
            result.add(user);
        }

        if(userList.size()>0){
            map.put("code", 200);
            map.put("msg", "成功");
            map.put("list", userList);
        }else{
            map.put("code", -1);
            map.put("msg", "获取失败");
        }
        return map;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delUser",method = RequestMethod.POST)
    public Object delUser(@RequestBody User user){
        int id = user.getId();
        System.out.println("ids:"+id);

        String value = this.getCookie();
        if(value==null) return map;

        String[] lists = value.split("-");

        System.out.println("lists:"+value);
        System.out.println("contains:"+Arrays.asList(lists).contains("0"));

        User user1 = userService.selectById(id);
        /**
         * 超 或 删
         */
        if(user1.getLimits().indexOf("0")!=-1){ //删除超的时候
            map.put("code", -1);
            map.put("msg", "不能删除超级管理员");
            return map;
        }
        if(Arrays.asList(lists).contains("0") || Arrays.asList(lists).contains("2")){

            int delUser = userService.delUser(id);

            if(delUser>0){
                map.put("code", 200);
                map.put("msg", "成功");
                map.put("list", delUser);
            }else{
                map.put("code", -1);
                map.put("msg", "删除失败");
            }

        }else {
            map.put("code", -1);
            map.put("msg", "没有权限");
        }

        return map;
    }





    /**
    * @desc: 登录
    */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Object login(@RequestBody User user){


        Map map = new HashMap();
        String username = user.getUserName();
        String password = user.getPassword();

//        String mdrandom = MD5.stringToMD5(password);

//        user.setPsUuid(mdrandom);

        if(username!=null && password!=null){
            List<User> userList = userService.login(username);
            if(userList.size()!=0){
                String limits = userList.get(0).getLimits();
                String UUID = userList.get(0).getPsUuid();

                System.out.println("limits:"+limits.replace(",", "-"));

                String password1 = userList.get(0).getPassword();
                    if(password.equals(password1)){
                        //添加cookie
                        COOKIEUtil.addCookie(response, limits.replace(",", "-"), username, UUID, 3600*10);

                        map.put("id",userList.get(0).getId());
                        map.put("username",userList.get(0).getUserName());
                        map.put("code",200);
                        map.put("msg","登录成功");
                    }else{
                        map.put("code",-1);
                        map.put("msg","登录失败");
                    }

            }else{
                map.put("code",-1);
                map.put("msg","账号不存在");
            }
        }else{
            map.put("code",-1);
            map.put("msg","账号和密码不能为空");
        }
        return map;
    }



    /**
    * @desc: 重置密码
    */
    @RequestMapping("/user/resetPassword")
    public Object resetPassword(String email) throws Exception {
        List<User> userList = userService.queryForEmail(email);
        String random = "";
        for(int i = 0; i < 8; i ++){
//            random += Math.random()*6;
            int r = (int) Math.floor(Math.random() * 10);
            random += r;
        }


        String mdrandom = MD5.stringToMD5(random);

        String uuid = UUID.randomUUID().toString();//转化为String对象
        uuid = uuid.replace("-","");//去掉-
        System.out.printf("random:"+random);
        Map map = new HashMap();
        if(userList.size()==0) {
            map.put("code", -1);
            map.put("msg", "邮箱暂未注册");
        }else{

            int reset = userService.resetPass(email,mdrandom,uuid);

            if(reset>0){
                sendMail.updatePass(email,random);
                map.put("code", 200);
                map.put("msg", "密码已发至邮箱，请前往查看");
            }else{
                map.put("code", -1);
                map.put("msg", "未知错误");
            }

        }
        return map;
    }

    /**
    * @Date 9:44 2020/11/30
    * @desc: 修改密码
    */
    @RequestMapping(value = "/user/updatePassword",method = RequestMethod.POST)
    public Object updatePass(@RequestBody User user){

        Map map = new HashMap();

        int id = user.getId();

        String password = user.getPassword();

//        String newPassword = list.get(0).;

        String uuid = UUID.randomUUID().toString();//转化为String对象
        uuid = uuid.replace("-","");//去掉-


        //获取cookie
        Cookie c = COOKIEUtil.getCookieByName(request,"bUsername");

//        String uuid = c.getValue();
//        System.out.println("uuid:"+uuid);

        if(c==null){
            map.put("code",13);
            map.put("msg","请登录");

        }else if(id>0 && password!=null){

            List<User> userList = userService.queryId(id);
            if(userList.size()!=0){
                int rUid = userService.updatePass(id,password,uuid);
                if(rUid>0){
                    map.put("code",200);
                    map.put("msg","修改成功");
                }else{
                    map.put("code",-1);
                    map.put("msg","修改失败");
                }

            }else{
                map.put("code",-1);
                map.put("msg","用户不存在");
            }
        }else{
            map.put("code",-1);
            map.put("msg","用户和密码不能为空");
        }

        return map;
    }


    /**
    * @Date 14:00 2020/11/30
    * @desc:
    */
    @RequestMapping("/user/logout")
    public Object logout(String uuid){
        Map map = new HashMap();
        Cookie c = COOKIEUtil.getCookieByName(request,"bUsername");
        if(c!=null){
            if(c.getValue().equals(uuid)){
                boolean b = COOKIEUtil.delCookie(response,request,"bUsername");
                if(b){
                    map.put("code",200);
                    map.put("msg","退出成功");
                }else{
                    map.put("code",13);
                    map.put("msg","请登录");
                }
            }else{
                map.put("code",13);
                map.put("msg","请登录");
            }
        }else{
            map.put("code",13);
            map.put("msg","请登录");
        }


        return map;
    }



    @RequestMapping("/user/queryAll")
    public Object queryAll(){
        return userService.queryAll();
    }

}


//[{
////    name:"",
////        pay:int
////        }]
